<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button v-allow="'import_employee'" type="danger" size="small" @click="hExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" width="75px">
            <template v-slot="{row}">
              <ImageHolder :src="row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formatEmployment(row.formOfEmployment) }}

            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页组件 -->
          <!-- 分页组件 -->
          <!-- current-page  当前页 -->
          <!-- page-sizes  设置每页显示多少条的选项 -->
          <!-- page-size 每页显示多少条 -->
          <!-- total 总条数 -->
          <!-- size-change 当page-size 发生变化时触发  -->
          <!-- current-change 当前页发生变化时触发 -->
          <el-pagination
            :current-page="pageparams.page"
            :page-sizes="[10,15,20]"
            :page-size="pageparams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      v-if="showDialog"
      title="新增员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
    >
      <addor-edit @close="hClose" @success="hSuccess" />
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <assignRole v-if="showDialogRole" ref="roleForm" :user-id="userId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import addorEdit from './empDialog.vue'
import { delEmployee, getEmployee } from '@/api/employees'
import empConstant from '@/constant/employees'
import assignRole from './assignRole.vue'
const hireMap = {}
empConstant.hireType.forEach(item => {
  hireMap[item.id] = item.value
})
export default {
  components: { 'addor-edit': addorEdit, assignRole },
  data() {
    return {
      pageparams: {
        page: 1,
        size: 10
      },
      total: 0,
      employees: [],
      showDialog: false,
      showDialogRole: false,
      userId: ''

    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployee(this.pageparams).catch(e => console.log('获取员工信息失败:', e))
      // console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
    },
    formatEmployment(code) {
      return hireMap[code]
    },
    hSizeChange(val) {
      this.pageparams.size = val
      this.loadEmployees()
    },
    hCurrentChange(val) {
      this.pageparams.page = val
      this.loadEmployees()
    },
    async hDel(id) {
      // 1.提示用户
      const result = await this.$confirm('您确定要删除吗?', '提示', {
        type: 'warning'
      })
      if (result !== 'confirm') return
      // 删除异常处理
      if (this.employees.length === 1 && this.pageparams.page > 1) {
        this.pageparams.page--
      }
      // 2.发请求那结果
      const res = await delEmployee(id).catch(e => this.$message.error(e.message))
      // 3.根据结果提示用户
      this.$message.success(res.message)
      // 4.重新获取数据
      this.loadEmployees()
    },
    hClose() {
      this.showDialog = false
    },
    hSuccess() {
      // 关闭对话框
      this.showDialog = false
      this.total++
      this.pageparams.page = Math.ceil(this.total / this.pageparams.size)
      // 重新获取
      this.loadEmployees()
    },
    async hExport() {
      const excel = await import('@/vendor/Export2Excel.js')
      const res = await getEmployee({ page: 1, size: this.total }).catch(e => e)
      if (!res.success) return console.dir(res)
      // console.log(res.data.rows)
      // 将数据转换成需要的格式
      const { header, data } = this.format2Excel(res.data.rows)
      // 导出Excel
      excel.export_json_to_excel({
        header, // 表头 必填
        data,
        // data: [
        //   ['刘备', 100],
        //   ['关羽', 500]
        // ], // 具体数据 必填
        filename: '员工信息表', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    },
    format2Excel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      // 如果数组的长度为0就说明没有数据,直接return 返回空的 header,data
      if (list.length === 0) return { header, data }
      // 创建1个obj为数组里面的第一条数据
      const obj = list[0]
      // 提取出数组的 键 循环映射出来  ,mapInfo.k能拿到后面的中文
      header = Object.keys(obj).map(k => mapInfo[k])
      // console.log(header)
      // 通过观察发现,就是将数组里面的每个数据对象,转到数组中的每个数组 -> 对象转成数组 (只要value不要key)
      data = list.map(item => { // item:{username:'管理员',...}
        const k = item.formOfEmployment
        item.formOfEmployment = hireMap[k]
        return Object.values(item) // 提取数组里面的值
      })
      console.log(data)
      return { header, data }
    },
    async  hAssignRole(id) {
      this.userId = id
      this.showDialogRole = true
      // 加一个 nextTick 就好了
      // 原因: props 的更新是异步的
      await this.$nextTick()
      // 调用子组件的方法让它发请求获取数据即可
      this.$refs.roleForm.loadRolesById()
    }
  }
}

</script>
